import { ACCESS_TOKEN,ACCESS_TOKEN_IP,INFORMATION,CENTER,COMMISSION } from "@/store/mutation-types"
import router from '@/router'
import Vue from 'vue'

export function timeFix() {
  const time = new Date()
  const hour = time.getHours()
  return hour < 9 ? '早上好' : (hour <= 11 ? '上午好' : (hour <= 13 ? '中午好' : (hour < 20 ? '下午好' : '晚上好')))
}

export function welcome() {
  const arr = ['休息一会儿吧', '我猜你可能累了']
  let index = Math.floor((Math.random() * arr.length))
  return arr[index]
}
export function deleteDynamicRouters(fullPath){
  let dynamicRouters = sessionStorage.getItem('DynamicRouters');
  let dynamicRoutersNew = [];
  if(dynamicRouters && dynamicRouters.length>0){
    dynamicRoutersNew = JSON.parse(dynamicRouters);
  }
  let index = 0;
  if(dynamicRoutersNew && dynamicRoutersNew.length>0){
    for (let i=0;i<dynamicRoutersNew.length;i++) {
      if (dynamicRoutersNew[i].path === fullPath) {
        index = i;
        break;
      }
    }
    dynamicRoutersNew.splice(index,1)
  }
  sessionStorage.setItem("DynamicRouters", JSON.stringify(dynamicRoutersNew));
}
export function addWWWHttpUrl(url) {
  if(!url){
    return '';
  }
  if (url.indexOf("bisp://cmd/?指定浏览器打开链接||") == 0) {
    if (IEUp8Version()) {
      url = url.replace("bisp://cmd/?指定浏览器打开链接||", "");
      return url;
    }
  }else if (url.indexOf("bisp://cmd/?openlinkbywebbrowser||") == 0) {
    if (IEUp8Version()) {
      url = url.replace("#", "");
    }
    else {
      url = url.replace("bisp://cmd/?openlinkbywebbrowser||", "").replace("▲ie", "");
    }
    return url;
  }else if(url.startsWith('ftp://')){
      return url;
  } else {
    if (url != null && url.indexOf("/") !== 0) {
      return url
    } else {
      let ticket = Vue.ls.get(ACCESS_TOKEN);
      let UserIP = "&UserIP="+ Vue.ls.get(ACCESS_TOKEN_IP)
      if (url.substring(0, 1) == "/") {
        return process.env.VUE_APP_ADD_HTTP + "/login.xip?LoginMethod=ssologin&Ticket=" + ticket +UserIP + "&ReturnUrl=" + encodeURIComponent(url.trim())
      } else {
        return process.env.VUE_APP_ADD_HTTP + "/login.xip?LoginMethod=ssologin&Ticket=" + ticket +UserIP + "&ReturnUrl=" + encodeURIComponent("/" + url.trim())
      }
    }
  }
}

function getChildrenTree(obj, data) {
  let children = []
  for (let i = 0; i < data.length; i++) {
    if (data[i].BcrParentid == obj.BcrId) {
      getChildrenTree(data[i], data)
      let routerData = {
        route: 1,
        id: data[i].BcrId,
        name: data[i].BcrId,
        path: '/' + data[i].BcrId,
        redirect: null,
        component: 'layouts/IframePageView',
        meta: {
          icon: 'dashboard',
          title: data[i].BcrName,
          keepAlive: 'true',
          isIFrame:true,
          url: addWWWHttpUrl(data[i].BcrParam2)
        },
        children: data[i].children
      }
      children.push(routerData)
    }
  }
  if (children.length > 0) {
    obj.children = children
  }
  obj.id = obj.BcrId,
  obj.route = 1,
  obj.name = obj.BcrId,
  obj.path = '/' + obj.BcrId,
  obj.redirect = null,
  obj.component = 'layouts/IframePageView',
  obj.meta = {
    icon: 'dashboard',
    title: obj.BcrName,
    keepAlive: 'true',
    isIFrame:true,
    url: addWWWHttpUrl(obj.BcrParam2)
  }
  return obj
}

/**
 * 构造菜单树，和路由
 * @author denggang
 * @param null
 * @exception
 * @return
 * @date 2019/5/27 10:22
 */
export function treeUtils(data) {
  let xtreeJson = []
  let typeJson = [];
  //初始化顶部菜单展示权限
  Vue.ls.set(INFORMATION,true)
  Vue.ls.set(CENTER,true)
  Vue.ls.set(COMMISSION,true)
  for (let i = 0; i < data.length; i++) {
    if (data[i].BcrParentid == 0) {
      let children = getChildrenTree(data[i], data)
      xtreeJson.push(children)
    }
    // else if(data[i].TypeId == 9){
    //   if(data[i].BcrId == 4149){
    //       Vue.ls.set(INFORMATION,false)
    //   }else if(data[i].BcrId == 1542){
    //       Vue.ls.set(CENTER,false)
    //   }else if(data[i].BcrId == 4148){
    //       Vue.ls.set(COMMISSION,false)
    //   }
    //   typeJson.push(data[i]);
    // }
  }
  // let typeJsons = [];
  // for (let i = 0; i < typeJson.length; i++) {
  //   let typeJsonChildren = getChildrenTree(typeJson[i], data)
  //   typeJsons.push(typeJsonChildren)
  // }
  // console.log(typeJsons);
  //信息中心1542  局内信息4149  市规委会4148
  // if(obj.MenuId == 4149){
  //   Vue.ls.set(INFORMATION,false)
  // }else if(obj.MenuId == 1542){
  //   Vue.ls.set(CENTER,false)
  // }else if(obj.MenuId == 4148){
  //   Vue.ls.set(COMMISSION,false)
  // }

  return xtreeJson
}
/**
 * 统一打开外部链接的方法
 * @author denggang
 * @date 2019/5/31 12:07
 */
export function openIFrame(name,path,title,url) {
  let newRou = {
      path: "/DYFrame"+path,
      name: name,
      component: resolve => require(['@/components/layouts/IframeComponent'], resolve),
      meta: {
        title:title ,
        isIFrame:true,
        url:url
      }
  };
  //判断是否需要添加到路由表，以免重复添加
  let addFlags = false;
  //获取sessionStorage里面添加的动态路由，将新路由加入然后再存入sessionStorage中
  let dynamicRouters = sessionStorage.getItem('DynamicRouters');
  let dynamicRoutersNew = [];
  if(dynamicRouters && dynamicRouters.length>0){
    dynamicRoutersNew = JSON.parse(dynamicRouters);
  }
  dynamicRoutersNew.forEach(item=>{
    if(item.name==name){
      addFlags = true;
    }
  });
  //需要添加
  if(!addFlags){
    dynamicRoutersNew.push(newRou);
    sessionStorage.setItem("DynamicRouters", JSON.stringify(dynamicRoutersNew));
    router.$addRoutesIFrame();
  }

}
/**
 * 触发 window.resize
 */
export function triggerWindowResizeEvent() {
  let event = document.createEvent('HTMLEvents')
  event.initEvent('resize', true, true)
  event.eventType = 'message'
  window.dispatchEvent(event)
}

/**
 * 过滤对象中为空的属性
 * @param obj
 * @returns {*}
 */
export function filterObj(obj) {
  if (!(typeof obj == 'object')) {
    return
  }

  for (var key in obj) {
    if (obj.hasOwnProperty(key)
      && (obj[key] == null || obj[key] == undefined || obj[key] === '')) {
      delete obj[key]
    }
  }
  return obj
}

/**
 * 时间格式化
 * @param value
 * @param fmt
 * @returns {*}
 */
export function formatDate(value, fmt) {
  var regPos = /^\d+(\.\d+)?$/
  if (regPos.test(value)) {
    //如果是数字
    let getDate = new Date(value)
    let o = {
      'M+': getDate.getMonth() + 1,
      'd+': getDate.getDate(),
      'h+': getDate.getHours(),
      'm+': getDate.getMinutes(),
      's+': getDate.getSeconds(),
      'q+': Math.floor((getDate.getMonth() + 3) / 3),
      'S': getDate.getMilliseconds()
    }
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (getDate.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    for (let k in o) {
      if (new RegExp('(' + k + ')').test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
      }
    }
    return fmt
  } else {
    //TODO
    value = value.trim()
    return value.substr(0, fmt.length)
  }
}

// 生成首页路由
export function generateIndexRouter(data) {
  let indexRouter = [{
    path: '/',
    name: 'home',
    //component: () => import('@/components/layouts/BasicLayout'),
    component: resolve => require(['@/components/layouts/TabLayout'], resolve),
    meta: { title: '首页' },
    redirect: '/home/index',
    children: [
      ...generateChildRouters(data)
    ]
  }, {
    'path': '*', 'redirect': '/404', 'hidden': true
  }]
  //获取sessionStorage中的动态路由并添加到路由表中
  let dynamicRouters = sessionStorage.getItem('DynamicRouters');
  if(dynamicRouters && dynamicRouters.length>0){
    let dRouters = JSON.parse(dynamicRouters);
    dRouters.forEach(item => {
      item.component = resolve => require(['@/components/layouts/IframePageView.vue'], resolve),
      indexRouter[0].children.push(item);
    })
  }
  return indexRouter
}

// 生成嵌套路由（子路由）

function generateChildRouters(data) {
  const routers = []
  for (var item of data) {
    let component = ''
    if (item.component.indexOf('layouts') >= 0) {
      component = 'components/' + item.component
    } else {
      component = 'views/' + item.component
    }
    let menu = {
      path: item.path,
      name: item.name,
      redirect: item.redirect,
      component: resolve => require(['@/' + component + '.vue'], resolve),
      hidden: item.hidden,
      meta: {
        title: item.meta.title,
        icon: item.meta.icon,
        url: item.meta.url,
        isIFrame:item.meta.isIFrame,
        permissionList: item.meta.permissionList
      }
    }
    if (item.alwaysShow) {
      menu.alwaysShow = true
    }
    if (item.children && item.children.length > 0) {
      menu.children = [...generateChildRouters(item.children)]
    }
    //--update-begin----author:scott---date:20190320------for:根据后台菜单配置，判断是否路由菜单字段，动态选择是否生成路由（为了支持参数URL菜单）------
    //判断是否生成路由
    if (item.route && item.route === '0') {
      console.log(' 不生成路由 item.route：  ' + item.route)
      console.log(' 不生成路由 item.path：  ' + item.path)
    } else {
      routers.push(menu)
    }
    //--update-end----author:scott---date:20190320------for:根据后台菜单配置，判断是否路由菜单字段，动态选择是否生成路由（为了支持参数URL菜单）------
  }
  return routers
}

/**
 * 深度克隆对象、数组
 * @param obj 被克隆的对象
 * @return 克隆后的对象
 */
export function cloneObject(obj) {
  return JSON.parse(JSON.stringify(obj))
}

/**
 * 随机生成数字
 * @param min 最小值
 * @param max 最大值
 * @return int 生成后的数字
 */
export function randomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

/**
 * 随机生成字符串
 * @param length 字符串的长度
 * @param chats 可选字符串区间（只会生成传入的字符串中的字符）
 * @return string 生成的字符串
 */
export function randomString(length, chats) {
  if (!length) length = 1
  if (!chats) chats = '0123456789qwertyuioplkjhgfdsazxcvbnm'
  let str = ''
  for (let i = 0; i < length; i++) {
    let num = randomNumber(0, chats.length - 1)
    str += chats[num]
  }
  return str
}

/**
 * 随机生成uuid
 * @return string 生成的uuid
 */
export function randomUUID() {
  let chats = '0123456789abcdef'
  return randomString(32, chats)
}

/**
 *
 * 处理url
 */
export function handleUrl(data) {
  //截取url
  let url = data.split(',')[0].replace('OpenNewForm(', '').replace('\'', '')
  //特殊处理邮件地址，使其页面刷新
  if (url.indexOf('/Modules/Mail/Mail.aspx') >= 0) {
    if (url.indexOf('/Modules/Mail/Mail.aspx?') >= 0) {
      url = url.replace('/Modules/Mail/Mail.aspx?', '/Modules/Mail/Mail.aspx?t=' + (new Date()).getTime() + '&')
    } else {
      url = url.replace('/Modules/Mail/Mail.aspx', '/Modules/Mail/Mail.aspx?t=' + (new Date()).getTime())
    }
  }

  if (url.indexOf('bisp://cmd/?指定浏览器打开链接||') == 0) {
    if (IEUp8Version()) {
      url = url.replace('bisp://cmd/?指定浏览器打开链接||', '')
    }
  } else if (url.indexOf('bisp://cmd/?openlinkbywebbrowser||') == 0) {
    if (IEUp8Version()) {
      url = url.replace('#', '')
    } else {
      url = url.replace('bisp://cmd/?openlinkbywebbrowser||', '').replace('▲ie', '')
    }
  }
  //omvc = window.open(url, key);
  //if (omvc && omvc.open && !omvc.closed)
  //    omvc.focus();
  return url;
}

export function IEUp8Version() {
  var userAgent = navigator.userAgent //取得浏览器的userAgent字符串
  var isIE = userAgent.indexOf('compatible') > -1 && userAgent.indexOf('MSIE') > -1 //判断是否IE浏览器
  var isEdge = userAgent.indexOf('Windows NT 6.1; Trident/7.0;') > -1 && !isIE //判断是否IE的Edge浏览器
  if (isIE) {
    var reIE = new RegExp('MSIE (\\d+\\.\\d+);')
    reIE.test(userAgent)
    var fIEVersion = parseFloat(RegExp['$1'])
    if (fIEVersion == 7) {
      return false
    } else if (fIEVersion == 8) {
      return false
    } else if (fIEVersion == 9) {
      return true
    } else if (fIEVersion == 10) {
      return true
    } else if (fIEVersion == 11) {
      return true
    } else {
      return false
    } //IE版本过低
  } else if (isEdge) {
    return true
  } else {
    return true //非IE
  }
}

/**
 * 【顶部导航栏模式】
 *  @date 2019-04-08
 *  顶部导航栏滚动条位置滚动到选中的菜单处
 * @param doc document 对象
 */
export function topNavScrollToSelectItem(doc) {
  let scrollWidth = doc.getElementById('top-nav-scroll-width')
  if (scrollWidth == null) return
  let menu = scrollWidth.getElementsByClassName('ant-menu')[0]
  if (menu) {
    let menuItems = menu.getElementsByTagName('li')
    for (let item of menuItems) {
      let index1 = item.className.indexOf('ant-menu-item-selected') !== -1
      let index2 = item.className.indexOf('ant-menu-submenu-selected') !== -1
      if (index1 || index2) {
        // scrollLeft = 选中项left - 选中项width - (第一个隐藏的div的宽度)
        let scrollLeft = (item.offsetLeft - item.offsetWidth - (index1 ? 100 : 60))
        let scrollView = doc.getElementById('top-nav-scroll-view')
        // scrollTo() 方法存在兼容性问题
        if (typeof scrollView.scrollTo === 'function') {
          scrollView.scrollTo({
            left: scrollLeft,
            behavior: 'smooth'
          })
        } else {
          scrollView.scrollLeft = scrollLeft
        }
        break
      }
    }
  }
}

/**
 * 获取本周日期
 */
export function getCurrentWeekDate(){
  let now = new Date(); //当前日期
  let nowDayOfWeek = now.getDay() - 1 ; //今天本周的第几天
  let nowDay = now.getDate(); //当前日
  let nowMonth = now.getMonth(); //当前月
  let nowYear = now.getYear(); //当前年
  let weekStartDate = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
  let weekEndDate = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
  return format(weekStartDate) + "-" + format(weekEndDate);
}

//格式化日期：MM月dd日
export function format(date) {
  var mymonth = date.getMonth()+1;
  var myweekday = date.getDate();

  if(mymonth < 10){
    mymonth = "0" + mymonth;
  }
  if(myweekday < 10){
    myweekday = "0" + myweekday;
  }
  return (mymonth + "月" + myweekday + "日");
}
